function resolve(data) {
    var self = this;

    if(self.status !== 'PENDING') return;

    setTimeout(function() {
        self.status = 'FULFILLED';
        self.data = data;
        // 依次执行成功之后的函数栈
        for(var i = 0; i < self.onResolvedCallback.length; i++) {
            self.onResolvedCallback[i](data);
        }
    });
}

function reject(reason) {
    var self = this;

    if(self.status !== 'PENDING') return;

    setTimeout(function() {
        self.status = 'REJECTED';
        self.reason = reason;
        // 依次执行失败之后的函数栈
        for(var i = 0; i < self.onRejectedCallback.length; i++) {
            self.onRejectedCallback[i](reason);
        }
    });
}

function Promise(executor) {
    var self = this;                 // Promise实例
    self.status = 'PENDING';         // Promise当前的状态
    self.data = undefined;           // Promise的成功值
    self.reason = undefined;         // Promise的失败原因
 
    self.onResolvedCallback = [];    // Promise resolve时的回调函数集
    self.onRejectedCallback = [];    // Promise reject时的回调函数集

    try{																										// 将上面实现的resolve和reject绑定当前上下文
        executor(resolve.bind(self), reject.bind(self));    // 执行executor并传入相应的参数
    } catch(e) {
        reject(e);
    }

}
function isObject(fn) {						// 用于判断是否是对象
    return typeof fn === 'object';
}

function isFunction(fn) {					// 用于判断是否是函数
    return typeof fn === 'function';
} 

function resolvePromise(promise, result, resolve, reject) {
    // 循环引用检测
    if(promise === result) {
        return reject(new TypeError("循环引用"));
    }

    // 如果回调为promise实例，则继续对回调的结果进行解析
    if(result instanceof Promise) {
        result.then(function(newResult) {
            resolvePromise(promise, newResult, resolve, reject);
        }, reject);
    }else if( isObject(result) || isFunction(result) ) {
        // 如果回调为对象或者函数
        if(result === null) {
            return resolve(result);
        }

        var then;
        try{
            then = result.then;
        } catch(error) {
            return reject(error);
        }
        
        if(isFunction(then)) {            
            var called = false;
            try{
                var thenLock = function(fn) {
                    if(called) return;
                    called = true;
                    fn && fn();
                };

                then.call(
                    result,
                    function(nextResult) {
                        thenLock(function() {
                            resolvePromise(promise, nextResult, resolve, reject);
                        });
                    }, 
                    function(e) {
                        thenLock(function() {
                            reject(e);
                        });        
                    }
                );
            } catch(error) {
                thenLock(function() {
                    reject(error);
                });
            }
        }else {
            resolve(result);
        }
    }else{          // 如果回调既不是promise又不是对象或函数
        resolve(result);
    }
}

// 添加then方法，返回新的promise从而实现链式调用
Promise.prototype.then=function(onResolved, onRejected) {
    // 如果两个参数不是函数，则造成值穿透
    onResolved = isFunction(onResolved) ? onResolved 
                                        : function(data) {
                                            return data; 
                                        }; 
    onRejected = isFunction(onRejected) ? onRejected
                                        : function(reason) {
                                            throw reason;
                                        };

    var self = this;
    var promise = new Promise(function(resolve, reject) {
        // 实现异步：将回调函数暂存到数组中
        if(self.status === 'PENDING') {
            // 存放成功回调
            self.onResolvedCallback.push(function() {
                setTimeout(function() {
                    try{
                        resolvePromise(promise, onResolved(self.data), resolve, reject);
                    } catch(e) {
                        reject(e);
                    }
                });
            });
            // 存放失败回调
            self.onRejectedCallback.push(function() {
                setTimeout(function() {
                    try{
                        resolvePromise(promise, onRejected(self.reason), resolve, reject);
                    } catch(e) {
                        reject(e);
                    }
                });
            });
        }
        if(self.status === 'FULFILLED') {
            setTimeout(function() {
                try{
                    resolvePromise(promise, onResolved(self.data), resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        }
        if(self.status === 'REJECTED') {
            setTimeout(function() {
                try{
                    resolvePromise(promise, onRejected(self.reason), resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });           
        }
    });    
    return promise;
};
Promise.deferred = function() {
    var res = {};
    res.promise = new Promise(function(resolve, reject) {
        res.resolve = resolve;
        res.reject = reject;
    });
    return res;
}
module.exports = Promise;